package com.hyphenate.easeui.widget.chatrow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Spannable;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.adapter.EaseMessageAdapter;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.exceptions.HyphenateException;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

public class EaseChatRowText extends EaseChatRow {

    private TextView contentView;
    private RelativeLayout bubble;

    public EaseChatRowText(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflatView() {
        inflater.inflate(
            message.direct() == EMMessage.Direct.RECEIVE ? R.layout.ease_row_received_message
                : R.layout.ease_row_sent_message, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);
        bubble = (RelativeLayout) findViewById(R.id.bubble);
    }

    /**
     * 根据weichat和ctrlType ，判断是否为满意度评价！
     * @param message
     * @return
     */
    private boolean isEvaluateMessage(EMMessage message) {
        boolean boo = false;
        try {
            JSONObject weichatString = message.getJSONObjectAttribute("weichat");
            String type = weichatString.getString("ctrlType");
            if ("inviteEnquiry".equals(type)) {
                boo = true;
            }
        } catch (Exception e) {
            boo = false;
        }
        return boo;
    }

    @Override
    public void onSetUpView() {
        bubble.removeAllViews();
        bubble.addView(contentView);

        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
        Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
        // 设置内容
        contentView.setText(span, BufferType.SPANNABLE);

        //判断是否为机器人自动回复的非text内容，字段为 msgtype
        if (!StringUtils.isEmpty(message.getStringAttribute("msgtype", null))) {
            bubble.removeAllViews();
            // 设置内容
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            String txtBody2 = message.getStringAttribute("msgtype", null);
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(txtBody2);
                JSONObject jsonObject2 = jsonObject.getJSONObject("choice");
                String title = jsonObject2.getString("title");
                if (title != null) {
                    TextView textView = new TextView(context);
                    textView.setMaxWidth(ViewUtils.dip2px(context, 225));
                    textView.setTextColor(Color.BLACK);
                    textView.setText(title);
                    linearLayout.addView(textView);
                }
                JSONArray list = jsonObject2.getJSONArray("list");
                for (int i = 0; i < list.length(); i++) {
                    String str = (String) list.opt(i);
                    final TextView textView = new TextView(context);
                    textView.setMaxWidth(ViewUtils.dip2px(context, 225));
                    textView.setTextColor(Color.RED);
                    textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
                    textView.setText(str);
                    textView.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            EaseChatFragment fragment = ((EaseMessageAdapter) adapter).getDefineTarget();
                            if(fragment != null){
                                fragment.sendTextMessage(textView.getText()
                                .toString());
                            }
                        }
                    });
                    linearLayout.addView(textView);
                }

                bubble.addView(linearLayout);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //判断是否为邀请满意度评价  调用EMMessage的扩展消息，关键字段为weichat和ctrlType。
        if (isEvaluateMessage(message)) {
            bubble.removeAllViews();
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);

            TextView textView = new TextView(context);
            textView.setMaxWidth(ViewUtils.dip2px(context, 225));
            textView.setTextColor(Color.BLACK);
            textView.setText("请对我的服务做出评价");
            linearLayout.addView(textView);
            Button btn = new Button(context);
            btn.setText("立即评价");
            btn.setTextColor(Color.WHITE);
            btn.setBackgroundColor(getResources().getColor(color.gray_1));

            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    new AlertDialog.Builder(context).setTitle("评价")
                        .setNegativeButton("不满意", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "谢谢", 0).show();
                            }

                        }).setPositiveButton("满意", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "谢谢", 0).show();
                            }
                        }).show();
                }
            });
            linearLayout.addView(btn);

            bubble.addView(linearLayout);
        }

        handleTextMessage();
    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
            setMessageSendCallback();
            switch (message.status()) {
            case CREATE:
                progressBar.setVisibility(View.GONE);
                statusView.setVisibility(View.VISIBLE);
                // 发送消息
                //                sendMsgInBackground(message);
                break;
            case SUCCESS: // 发送成功
                progressBar.setVisibility(View.GONE);
                statusView.setVisibility(View.GONE);
                break;
            case FAIL: // 发送失败
                progressBar.setVisibility(View.GONE);
                statusView.setVisibility(View.VISIBLE);
                break;
            case INPROGRESS: // 发送中
                progressBar.setVisibility(View.VISIBLE);
                statusView.setVisibility(View.GONE);
                break;
            default:
                break;
            }
        } else {
            if (!message.isAcked() && message.getChatType() == ChatType.Chat) {
                try {
                    EMClient.getInstance().chatManager()
                        .ackMessageRead(message.getFrom(), message.getMsgId());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        // TODO Auto-generated method stub

    }

}
